<?php

namespace Func;

use \MemLib\PublicFunc;
use \MemLib\FuncBase;

/**
 * client_api基础数据接口功能函数
 * @version 1.0
 * @author 张云江
 */
class Func100000 extends FuncBase
{
    /**
     * 登录接口
     * @return mixed
     */
    public function F100001($device_id, $device_name, $device_model, $build_id, $c_ver, $c_type)
    {
        $MemOrder_Application_info = new \Mem\MemOrder_Application_info();
        $applictionInfo = $MemOrder_Application_info->getInfoWithbuild_id($build_id);
        if (empty($applictionInfo)) {
            return $this->returnData(RESULT_FAILED, "应用不存在");
        }
        $rdata = array();
        $rdata['c_ver'] = $c_ver;
        $rdata['c_type'] = $c_type;
        $rdata['user_id'] = 0;
        $rdata['is_vip'] = 0;
        $rdata['is_verify'] = 0; //是否需要验证 1.需要验证 0.不需要
        $rdata['vip_time'] = '';
        $rdata['app_info'] = $applictionInfo;
        $application_id = $applictionInfo['application_id'];
        $MemOrder_User_info = new \Mem\MemOrder_User_info();
        $uinfo = $MemOrder_User_info->getInfoWithdevice_id($device_id);
        if (empty($uinfo)) {
            $rdata['user_id'] = $MemOrder_User_info->insertDataWithParam($application_id, $device_id, $device_name, $device_model);
            $rdata['is_verify'] = 1;
        } else {
            $rdata['user_id'] = $uinfo['user_id'];
            $rdata['is_vip'] = $uinfo['vip'];
            $rdata['vip_time'] = $uinfo['vip_time'];
            //查询验证时间是否超出一天时间 12*60*60(半天)
            if (empty($uinfo['verify_time'])) {
                $rdata['is_verify'] = 1;
            } else {
                $date2 = time();
                $date1 = strtotime($uinfo['verify_time']);
                $diff = abs($date2 - $date1);
                if ($diff > 12 * 60 * 60) {
                    $rdata['is_verify'] = 1;
                } else {
                    $rdata['is_verify'] = 0;
                }
            }
            //更新登陆时间
            $upData = array(
                "login_time" => date("Y-m-d H:i:s", time()),
            );
            $wheredata = array(
                'user_id' => $uinfo['user_id']
            );
            $MemOrder_User_info->updateDataWithParam($upData, $wheredata);
        }
        return $this->returnData(RESULT_SUCCESS, "", $rdata);
    }

    /**
     * 登录接口
     * $environment 1.测试环境 默认正式环境
     * @return mixed
     */
    public function F100002($device_id, $receipt_data, $password, $build_id, $environment, $verify_type, $c_ver, $c_type)
    {
        $msg = "验证失败";
        $rdata = array();
        $rdata['user_id'] = 0;
        $rdata['c_ver'] = $c_ver;
        $rdata['c_type'] = $c_type;
        $rdata['is_vip'] = 0;
        $rdata['vip_time'] = '';
        $rdata['product_id'] = '';
        $rdata['transaction_id'] = '';
        $rdata['consumables_state'] = 0; //消耗品验证状态 1.成功 0.重复验证

        $MemOrder_Application_info = new \Mem\MemOrder_Application_info();
        $applictionInfo = $MemOrder_Application_info->getInfoWithbuild_id($build_id);
        if (empty($applictionInfo)) {
            return $this->returnData(RESULT_FAILED, "应用不存在");
        }
        $application_id = $applictionInfo['application_id'];
        $environment_type = $applictionInfo['environment']; //应用当前所处环境 1.测试环境
        //在测试环境下，所有的苹果验证接口走沙盒环境
        if ($environment_type == 1) {
            $environment = 1;
        }
        $receipt_data = rawurldecode(urlencode($receipt_data));
        $application_password = $applictionInfo['application_password'];
        if (empty($application_password)) {
            $application_password = $password;
        }
        $resultData = PublicFunc::sendApple($receipt_data, $application_password, $environment);

        $MemOrder_info = new \Mem\MemOrder_info();
        $MemOrder_info_meta = new \Mem\MemOrder_info_meta();
        $MemOrder_Subscribe_info = new \Mem\MemOrder_Subscribe_info();

        $status = $resultData['status'];
        if ($status == 0) {
            //保存UserInfo 最后更新
            $msg = "验证成功";
            $user_vip = 0;
            $user_product_id = '';
            $user_vip_time = '';
            $user_transaction_id = '';
            $user_verify_time = date("Y-m-d H:i:s", time());

            $in_app = $resultData['receipt']['in_app'];
            $latest_receipt_info = $resultData['latest_receipt_info'];
            $pending_renewal_info = $resultData['pending_renewal_info'];
            //消耗品验证
            if (!empty($in_app) && $verify_type == 1) {
                foreach ($in_app as $orderInfo) {
                    $source_type = $environment;
                    $purchase_date = date("Y-m-d H:i:s", (float)$orderInfo['purchase_date_ms'] / 1000);
                    $product_id = $orderInfo['product_id'];
                    $transaction_id = $orderInfo['transaction_id'];
                    if (!empty($orderInfo['expires_date_ms'])) {
                        \Mlog::error('苹果内购验证 该商品为订阅商品 无需消耗品验证，transaction_id=' . $transaction_id);
                    } else {
                        $dborderinfo = $MemOrder_info->getInfoWithtransaction_id($transaction_id);
                        if (!empty($dborderinfo)) {
                            \Mlog::error('苹果内购验证 该商品已经验证 无需消耗品重复验证，transaction_id=' . $transaction_id);
                        } else {
                            //消耗品验证成功
                            $rdata['consumables_state'] = 1;
                            $rdata['product_id'] = $product_id;
                            $rdata['transaction_id'] = $transaction_id;

                            unset($orderInfo['purchase_date']);
                            unset($orderInfo['purchase_date_ms']);
                            unset($orderInfo['purchase_date_pst']);
                            unset($orderInfo['expires_date']);
                            unset($orderInfo['expires_date_ms']);
                            unset($orderInfo['expires_date_pst']);
                            unset($orderInfo['original_purchase_date']);
                            unset($orderInfo['original_purchase_date_ms']);
                            unset($orderInfo['original_purchase_date_pst']);
                            unset($orderInfo['product_id']);
                            unset($orderInfo['transaction_id']);
                            unset($orderInfo['original_transaction_id']);

                            $expires_date = $purchase_date; //对于消耗品 购买即过期
                            $order_id = $MemOrder_info->insertDataWithParam($product_id, $application_id, $transaction_id, $purchase_date, $expires_date, $source_type);
                            if (!empty($order_id)) {
                                //插入扩展字段
                                foreach ($orderInfo as $k1 => $value) {
                                    $MemOrder_info_meta->insertDataWithParam($order_id, $k1, $value, '');
                                }
                                //插入消耗品标识
                                $MemOrder_info_meta->insertDataWithParam($order_id, 'verify_type', 1, '');
                            }
                        }
                    }
                }
            }
            //订单列表
            if (!empty($latest_receipt_info)) {
                foreach ($latest_receipt_info as $orderInfo) {
                    $source_type = $environment;
                    $purchase_date = date("Y-m-d H:i:s", (float)$orderInfo['purchase_date_ms'] / 1000);
                    $expires_date = date("Y-m-d H:i:s", (float)$orderInfo['expires_date_ms'] / 1000);
                    $product_id = $orderInfo['product_id'];
                    $transaction_id = $orderInfo['transaction_id'];
                    //判断会员是否过期
                    $date2 = time();
                    $date1 = (float)$orderInfo['expires_date_ms'] / 1000;
                    $diff = $date1 - $date2;
                    $cancellation_date = $orderInfo['cancellation_date'];
                    if (!empty($cancellation_date)) {
                        \Mlog::error('苹果内购验证 用户已经退订 cancellation_date = ' . $cancellation_date . ' transaction_id = ' . $transaction_id);
                    }
                    if ($diff > 0 && empty($cancellation_date)) {
                        //会员未过期
                        $user_vip = 1;
                        $user_product_id = $product_id;
                        $user_vip_time = $expires_date;
                        $user_transaction_id = $transaction_id;

                        $rdata['is_vip'] = 1;
                        $rdata['vip_time'] = $expires_date;
                        $rdata['product_id'] = $product_id;
                        $rdata['transaction_id'] = $transaction_id;
                    }
                    $dborderinfo = $MemOrder_info->getInfoWithtransaction_id($transaction_id);
                    unset($orderInfo['purchase_date']);
                    unset($orderInfo['purchase_date_ms']);
                    unset($orderInfo['purchase_date_pst']);
                    unset($orderInfo['expires_date']);
                    unset($orderInfo['expires_date_ms']);
                    unset($orderInfo['expires_date_pst']);
                    unset($orderInfo['original_purchase_date']);
                    unset($orderInfo['original_purchase_date_ms']);
                    unset($orderInfo['original_purchase_date_pst']);
                    unset($orderInfo['product_id']);
                    unset($orderInfo['transaction_id']);
                    unset($orderInfo['original_transaction_id']);
                    if (empty($dborderinfo)) {
                        //不存在 插入
                        $order_id = $MemOrder_info->insertDataWithParam($product_id, $application_id, $transaction_id, $purchase_date, $expires_date, $source_type);
                        if (!empty($order_id)) {
                            //插入扩展字段
                            foreach ($orderInfo as $k1 => $value) {
                                $MemOrder_info_meta->insertDataWithParam($order_id, $k1, $value, '');
                            }
                        }
                    } else {
                        //存在 更新
                        $order_id = $dborderinfo['order_id'];
                        $wheredata = array("order_id" => $order_id);
                        $MemOrder_info_meta->delDataWithList_id($wheredata);
                        foreach ($orderInfo as $k1 => $value) {
                            $MemOrder_info_meta->insertDataWithParam($order_id, $k1, $value, '');
                        }
                    }
                }
            }
            //订阅情况
            if (!empty($pending_renewal_info)) {
                foreach ($pending_renewal_info as $renewalinfo) {
                    $product_id = $renewalinfo['auto_renew_product_id'];
                    $transaction_id = $renewalinfo['original_transaction_id'];
                    $state = $renewalinfo['auto_renew_status'];
                    $expiration_intent = $renewalinfo['expiration_intent'];
                    $dbsubscribeinfo = $MemOrder_Subscribe_info->getInfoWithtransaction_id($transaction_id);
                    if (empty($dbsubscribeinfo)) {
                        $MemOrder_Subscribe_info->insertDataWithParam($product_id, $application_id, $transaction_id, $state, $expiration_intent);
                    } else {
                        $subscribe_id = $dbsubscribeinfo['subscribe_id'];
                        $upData = array(
                            "product_id" => $product_id,
                            "state" => $state,
                            "expiration_intent" => $expiration_intent,
                        );
                        $wheredata = array(
                            'subscribe_id' => $subscribe_id
                        );
                        $MemOrder_Subscribe_info->updateDataWithParam($upData, $wheredata);
                    }
                }
            }
            //更新用户信息
            $MemOrder_User_info = new \Mem\MemOrder_User_info();
            $userinfo = $MemOrder_User_info->getInfoWithdevice_id($device_id);
            if (!empty($userinfo)) {
                $user_id = $userinfo['user_id'];
                $rdata['user_id'] = $user_id;
                $upData = array(
                    "vip" => $user_vip,
                    "product_id" => $user_product_id,
                    "vip_time" => $user_vip_time,
                    "transaction_id" => $user_transaction_id,
                    "verify_time" => $user_verify_time,
                );
                $wheredata = array(
                    'user_id' => $user_id
                );
                $MemOrder_User_info->updateDataWithParam($upData, $wheredata);
            } else {
                \Mlog::error('苹果内购验证 更新用户会员信息失败 device_id = ' . $device_id);
            }
        } else {
            \Mlog::error('苹果内购验证失败status = ' . $resultData['status'] . ' device_id = ' . $device_id . ' build_id = ' . $build_id);
        }
        //保存base64数据
        $MemOrder_Receipt_info = new \Mem\MemOrder_Receipt_info();
        $receipt_info = $MemOrder_Receipt_info->getInfoWithdevice_id($device_id);
        if (empty($receipt_info)) {
            $MemOrder_Receipt_info->insertDataWithParam($device_id, $receipt_data);
        } else {
            $device_id = $receipt_info['device_id'];
            $upData = array(
                "receipt_data" => $receipt_data,
            );
            $wheredata = array(
                'device_id' => $device_id
            );
            $MemOrder_Receipt_info->updateDataWithParam($upData, $wheredata);
        }
        return $this->returnData($status, $msg, $rdata);
    }
}
